package com.dzm.portal.config;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 作者：Dzm
 * 时间：2024-09-09-16:24
 * 功能：
 */

@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class DxgCacheConfig {

    @Bean
    public RedisCacheConfiguration createConfiguration(CacheProperties cacheProperties) {
        //获取配置文件中的redis配置信息
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //获取redis缓存配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //设置键和值序列化类型
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        //设置redis缓存配置类中的配置
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());  //存货时间
        }

        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());    //key的前缀
        }

        if (!redisProperties.isCacheNullValues()) {//是否可以缓存空值，解决缓存传统问题
            config = config.disableCachingNullValues();
        }

        if (!redisProperties.isUseKeyPrefix()) {//是否设置启用键的前缀
            config = config.disableKeyPrefix();
        }

        return config;
    }
}
